<template>
    <up-notice-bar :text="text" speed="50"></up-notice-bar>
    <view style="padding: 5px;display: flex;justify-content: space-between;align-items: center;">
        <up-input style="flex: 1;" placeholder="请输入运单码" v-model="relateWaybillCode" :clearable="true">
            <template #prefix>
                <up-icon name="search"></up-icon>
            </template>
        </up-input>
        <up-button style="width: 50px;height: 38px;" type="primary" text="搜索" @click="search"></up-button>
    </view>
    <!-- 运单列表 -->
    <up-list @scrolltolower="scrolltolower" style="background-color: #eeebec;">
        <up-empty :iconSize="150" mode="order" text="当前暂无运单" v-if="waybillList.length === 0"></up-empty>
        <up-list-item v-for="item in waybillList" :key="item.id">
            <view class="header-huoyuan">
                <view class="huoyuan-all">
                    <view class="all-1">
                        所属项目：{{ item.projectName }}
                    </view>
                    <view class="orderId">
                        <up-copy :content="item.billId">
                            <text>订单号:{{ item.billId }}</text>
                        </up-copy>
                    </view>
                    <view class="orderId">
                        <up-copy :content="item.billNo">
                            <text>配载单号:{{ item.billNo }}</text>
                        </up-copy>
                    </view>
                    <view class="all-box">
                        <view class="all-left">
                            <view class="all-2">
                                装货时间：{{ item.waybillShipmentStartTime }}
                            </view>
                            <view class="all-3">
                                <view class="left-3">
                                    <view class="left-3-1">
                                        <view class="all-3-1">
                                            装
                                        </view>
                                        <view class="all-3-2">
                                            {{
                                                item.shipperaddress ? item.shipperaddress :
                                                    showAddress(item, 'initialAddress')
                                            }}
                                        </view>
                                    </view>
                                    <view class="left-3-2">
                                        <image src="../../static/images/icon/juli.png" mode=""></image>
                                        <view class="left-3-2-2" v-if="item.billMode == 'APPOINT'">
                                            指派模式
                                        </view>
                                        <view class="left-3-2-2" v-if="item.billMode == 'GRAB'">
                                            抢单模式
                                        </view>
                                    </view>
                                    <view class="left-3-3">
                                        <view class="all-3-3-1">
                                            卸
                                        </view>
                                        <view class="all-3-3-2">
                                            {{
                                                item.consigneeaddress ? item.consigneeaddress :
                                                    showAddress(item, 'endAddress')
                                            }}
                                        </view>
                                    </view>
                                </view>
                                <view class="right-3">
                                    <view class="right-3-1">
                                        {{ item.goodsName }}
                                    </view>
                                </view>

                            </view>
                            <view class="all-4">
                                <view class="all-4-1">
                                    {{ item.goodsCountShow }}
                                </view>
                                <view class="all-2">
                                    结束时间：{{ item.waybillShipmentEndTime }}
                                </view>
                            </view>
                        </view>
                        <view class="all-right" @click="ReceingOrders(item)">
                            <view class="right-text">
                                接单
                            </view>
                        </view>
                    </view>

                </view>
            </view>
        </up-list-item>
        <LoadMore :status="status" v-if="waybillList.length !== 0"></LoadMore>
    </up-list>

    <up-toast ref="uToastRef"></up-toast>

    <div style="position: fixed;top: 15%;right: 15px;z-index: 99999;" @click="scanQrcode"><up-icon size="50"
            name="scan"></up-icon></div>
</template>

<script lang="ts" setup>
import {
    ref,
    reactive,
    nextTick
} from "vue"
import {
    useWaybillShipCode,
    getDriverTask,
    SignForWaybill
} from "@/api/driver"
import {
    onShow, onLoad
} from "@dcloudio/uni-app"
import {
    getToken
} from "@/utils/auth"
import LoadMore from "@/components/LoadMore.vue"
import {
    storeToRefs
} from "pinia"
import {
    useUserStore
} from '@/store/modules/user'
import {
    showConfirm
} from '@/utils/common'

/* hooks */
const {
    role
} = storeToRefs(useUserStore())


/* 数据 */
const text = ref('接单后，十分钟后您还在小程序内的话，小程序会跟踪您的位置，从您的第一次定位开始，如果您中途离开小程序超过一个小时，系统会自动放弃此次运单的跟踪')
const relateWaybillCode = ref('')
//运单数组
const waybillList = reactive<any[]>([])
// 提示
const uToastRef = ref<any>(null)
//获取列表参数
const getListParams = reactive({
    currPage: 1,
    limit: 10,
    status: 'NOT_ACCEPTED_ORDER'
})
const status = ref<"loadmore" | "nomore" | "loading" | undefined>('loadmore')
// 列表数据还有没有下一页
const hasNextPage = ref(false)
// 是否正在扫码
const isScan = ref(false)



/* 函数 */
// 没有详细地址时显示省市区
const showAddress = (item: any, str: string) => {
    let address = JSON.parse(item[str])
    return address.provinceText + address.cityText + address.countyText + (address.text ? address.text : '')
}
// 使用运单码
const search = async () => {
    if (relateWaybillCode.value) {
        uToastRef.value.show({
            type: 'loading',
            message: "请稍等...",
            duration: -1
        })
        let res = await useWaybillShipCode({
            relateWaybillCode: relateWaybillCode.value
        })
        uToastRef.value.hide()
        if (res.success) {
            uToastRef.value.show({
                position: "top",
                type: 'success',
                message: "操作成功"
            })
            waybillList.length = 0
            getListParams.currPage = 1
            await getWaybillList(getListParams)
        }
    } else {
        uToastRef.value.show({
            position: "top",
            type: 'error',
            message: "请输入运单码"
        })
    }
}
// 获取运单
const getWaybillList = async (params: typeof getListParams) => {
    uToastRef.value.show({
        message: '加载中...',
        type: 'loading',
        duration: -1
    })
    let res = await getDriverTask(params)
    uToastRef.value.hide()
    if (res.success) {
        Object.assign(getListParams, params)
        hasNextPage.value = res.data.hasNextPage
        if (!res.data.hasNextPage) {
            status.value = "nomore"
        } else {
            status.value = "loadmore"
        }
        waybillList.push(...res.data.list)
    }
}
// 触底刷新
const scrolltolower = async () => {
    if (hasNextPage.value) {
        status.value = "loading"
        getListParams.currPage = getListParams.currPage++
        let params = {
            ...getListParams,
            currPage: getListParams.currPage + 1
        }
        await getWaybillList(params)
    } else {
        status.value = "nomore"
    }
}
// 接收订单
const ReceingOrders = async (item: any) => {
    let res = await showConfirm(text.value)
    if (!res.confirm) {
        return
    }
    if (item.billMode == 'GRAB') {
        let codeId = item.id
        let driverId = item.driverId
        uni.navigateTo({
            url: '/pages/work/receiving?codeId=' + codeId + '&driverId=' + driverId + '&unit=' +
                item.unit
        })
    } else if (item.billMode == 'APPOINT') {
        let params = {
            id: item.id,
            text: '接单',
            vehicleId: item.vehicleId,
            banId: item.banId
        }
        uToastRef.value.show({
            message: '正在接单',
            type: 'loading',
            duration: -1
        })
        let res = await SignForWaybill(params)
        uToastRef.value.hide()
        if (res.success) {
            uToastRef.value.show({
                position: "top",
                type: 'success',
                message: "已接单",
                duration: 1000,
                complete() {
                    waybillList.length = 0
                    getListParams.currPage = 1
                    getWaybillList(getListParams)
                }
            })
        }
    } else {
        uToastRef.value.show({
            position: "top",
            type: 'error',
            message: "出错啦，请联系管理员"
        })
    }
}
// 扫码前鉴权
const checkCameraPermission = async () => {
    try {
        const res: any = await uni.getSetting()
        if (!res.authSetting['scope.camera']) {
            // 未授权，请求权限
            const authRes = await uni.authorize({
                scope: 'scope.camera'
            })
            return true
        }
        return true
    } catch (err: any) {
        if (err.errMsg.includes('auth deny')) {
            uni.showModal({
                title: '提示',
                content: '需要相机或者相册权限才能使用该功能，请前往设置开启',
                success: (res) => {
                    if (res.confirm) {
                        // 跳转到小程序设置页
                        uni.openSetting()
                    }
                }
            })
        } else {
            uToastRef.value.show({
                position: "top",
                message: '未知错误' + err.errMsg,
                type: 'warning'
            })
        }
        return false
    }
}
// 点击扫描二维码
const scanQrcode = async () => {
    if (!getToken()) {
        uToastRef.value.show({
            position: "top",
            message: '请先登录',
            type: 'warning'
        })
        return
    }
    // 鉴权
    let permission = await checkCameraPermission()
    // 如果有权限
    if (permission) {
        if (isScan.value) return
        isScan.value = true
        uni.scanCode({
            scanType: ['qrCode'],
            success: async (res) => {
                if (res.result != 'null') {
                    relateWaybillCode.value = res.result
                    await search()
                } else {
                    uToastRef.value.show({
                        position: "top",
                        message: '扫码结果为空',
                        type: 'warning'
                    })
                }
            },
            fail: (err: any) => {
                uToastRef.value.show({
                    position: "top",
                    message: '已取消扫码或扫码失败',
                    type: 'warning'
                })
            },
            complete: () => {
                isScan.value = false
            }
        })
    }
}
// 初始化封装
const init = async () => {
    waybillList.length = 0
    // 因为下面请求中会调用uToastRef，onshow不能获取dom元素，所以需要nextTick
    await nextTick()
    if (getToken()) {
        if (role.value === "driver") {
            await getWaybillList(getListParams)
        } else {
            uToastRef.value.show({
                position: "top",
                message: '您不是司机，不能查看这里的运单',
                type: 'warning'
            })
        }
    } else {
        uToastRef.value.show({
            position: "top",
            message: '登录后才能看到运单',
            type: 'warning'
        })
    }
}


/* 钩子 */
// tabar每次点击不会触发其他钩子，只能写在onShow里
onShow(async () => {
    await init()
})
// 页面级配置分享转发
// #ifdef MP-WEIXIN
onLoad(() => {
    uni.showShareMenu({
        withShareTicket: true, // 是否使用带 shareTicket 的转发
        menus: ['shareAppMessage', 'shareTimeline'] // 可分享到朋友圈
    })
})
// #endif
</script>

<style lang="scss" scoped>
.header-huoyuan {

    background-color: white;

    .huoyuan-all {
        margin: 10px 0 10px 18px;
        padding: 15px 0 5px 0;

        &:first-child {
            margin: 0px 0 10px 18px;
        }

        .all-1 {
            font-size: 16px;
            font-weight: 400;
            margin: 0 0 7px 0;
        }

        .all-box {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;

            .all-left {

                .all-2 {
                    color: #999;
                }

                .all-3 {
                    display: flex;
                    margin-top: 12px;

                    .left-3 {
                        width: 180px;
                        margin-right: 10px;

                        .left-3-1 {
                            display: flex;

                            .all-3-1 {
                                background-color: green;
                                color: white;
                                border-radius: 50%;
                                padding: 4px 7px;
                                font-size: 15px;
                                margin-right: 18rpx;
                                height: 30px;
                            }

                            .all-3-2 {
                                font-size: 15px;
                                align-content: center;
                            }
                        }

                        .left-3-2 {
                            display: flex;
                            margin: 20px 0;

                            image {
                                width: 20px;
                                height: 20px;
                                margin-right: 20px;
                            }

                            .left-3-2-2 {
                                align-content: center;
                            }
                        }

                        .left-3-3 {
                            display: flex;

                            .all-3-3-1 {
                                background-color: red;
                                color: white;
                                border-radius: 50%;
                                padding: 4px 7px;
                                font-size: 15px;
                                margin-right: 18rpx;
                                height: 30px;
                            }

                            .all-3-3-2 {
                                font-size: 15px;
                                align-content: center;
                            }
                        }
                    }

                    .right-3 {
                        padding: 5px;

                        .right-3-1 {
                            color: dodgerblue;
                            font-size: 15px;
                            margin-bottom: 4px;
                        }

                        .right-3-2 {
                            font-size: 10px;
                            color: #999;
                            margin-bottom: 4px;
                        }

                        .right-3-3 {
                            display: flex;

                            .right-3-3-0 {
                                font-size: 9px;
                                color: #999;
                                align-content: center;
                                margin-right: 2px;
                            }

                            .right-3-3-1 {
                                color: red;
                                font-size: 18px;
                                margin-right: 5px;
                                font-weight: 500;
                            }

                            .right-3-3-2 {
                                font-size: 9px;
                                color: #999;
                                align-content: center
                            }
                        }
                    }
                }

                .all-4 {
                    display: flex;
                    margin-top: 20px;
                    align-items: center;

                    .all-4-1 {
                        color: #999;
                        font-size: 12px;
                        margin-right: 13px;
                    }

                    .all-4-2 {
                        display: flex;
                        color: red;

                        .all-4-2-1 {
                            align-content: center;

                            image {
                                width: 15px;
                                height: 15px;
                                margin-right: 5px;
                                line-height: 5px;
                            }
                        }

                        .all-4-2-2 {
                            align-content: center;
                        }

                    }
                }
            }

            .all-right {
                background-color: dodgerblue;
                display: flex;
                justify-content: center;
                align-items: center;
                width: 50px;

                .right-text {
                    color: white;
                    font-size: 17px;
                    text-align: center;
                }
            }
        }

        .orderId {
            color: #999;
            font-size: 16px;
            margin-bottom: 5px;
        }
    }
}
</style>